package com.chenggcode.security.jwt.service.impl;

import com.chenggcode.security.jwt.entity.UserInfo;
import com.chenggcode.security.jwt.repository.UserInfoRepository;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;

/**
 * @author Chenggcode
 * @date 2025/7/7 15:40
 */
@Component
@RequiredArgsConstructor
public class JwtService {
    private final UserInfoRepository repository;
    private static final String SECRET = "284957365AF548423FDC49585YDX9485FD99495JHG294HD983HPH90GN3UFD34H";
    @Value("${auth-token.expire-seconds:300}")
    private int authTokenExpireSeconds;
    @Value("${refresh-token.expire-seconds:604800}")
    private int refreshTokenExpireSeconds;

    public Map<String, String> geneToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        String accessToken = createToken(claims, username);
        String refreshToken = UUID.randomUUID().toString().replace("-", "");
        LocalDateTime refreshTokenExpiration = LocalDateTime.now().plusSeconds(refreshTokenExpireSeconds);
        repository.updateRefreshToken(username, refreshToken, refreshTokenExpiration);
        return Map.of(
                "accessToken", accessToken,
                "refreshToken", refreshToken
        );
    }

    public String refreshToken(String refreshToken) {
        UserInfo userInfo = repository.getByRefreshToken(refreshToken);
        if (Objects.isNull(userInfo) || userInfo.getRefreshTokenExpiration().isBefore(LocalDateTime.now())) {
            return null; // Refresh token is invalid or expired
        }
        Map<String, Object> claims = new HashMap<>();
        return createToken(claims, userInfo.getUsername());
    }

    public void disableRefreshToken(String username) {
        repository.updateRefreshToken(username, null, null);
    }

    private String createToken(Map<String, Object> claims, String username) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + authTokenExpireSeconds * 1000L))
                .signWith(getSignKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    private Key getSignKey() {
        byte[] keyBytes = Decoders.BASE64.decode(SECRET);
        return Keys.hmacShaKeyFor(keyBytes);
    }

    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    private Claims extractAllClaims(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSignKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    private Boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = extractUsername(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }
}
